import React, { useState, useEffect } from "react";
import { Tabs, Loading, Swiper, Image } from "react-vant";
import styles from "../css/Details.module.css";
import { useParams } from "react-router-dom";
import axios from "axios";
import { ActionBar } from "react-vant"; //底部导航栏
import { CartO, WapHome } from "@react-vant/icons"; //引入图标
import { useNavigate } from 'react-router-dom';

export default function Details() {
  const [emitInfo, setEmitInfo] = useState(null);

  const navigate = useNavigate();
  const { id } = useParams();
  // 使用 useState 管理数据和加载状态
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState(0);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.post("/mobile/index");
        const matchedItem = response.data.data.commodity.find(
          (item) => item.id == id
        );
        if (matchedItem) {
          setData(matchedItem);
        } else {
          setError("未找到该商品信息");
        }
      } catch (err) {
        setError("数据加载失败，请稍后重试");
        console.error("请求失败:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [id]); // 添加 id 到依赖数组

  // 加载状态
  if (loading) {
    return (
      <Loading
        style={{
          display: "inline-flex",
          position: "fixed",
          left: "50%",
          top: "50%",
          transform: "translate(-50%, -50%)",
        }}
        size="24px"
        vertical
      >
        加载中...
      </Loading>
    );
  }
  // 错误的状态
  if (error) {
    return <div className={styles.error}>{error}</div>;
  }
  // 数据不存在
  if (!data) {
    return <div className={styles.error}>商品信息不存在</div>;
  }

  // 标签页配置数据（使用动态数据）
  const tabContents = [
    {
      title: "商品",
      content: (
        <div>
          <div>{console.log(data)}</div>
          <div
            className={styles.demo_swiper}
            style={{
              padding: "0px",
              marginTop: "2px",
              height: "300px",
            }}
          >
            <Swiper autoplay={3000} touchable={true} preventScroll={true}>
              {data.banner.split(",").map((item) => (
                <Swiper.Item
                  touchable={true}
                  preventScroll={true}
                  key={item}
                  style={{ height: 300 }}
                >
                  {" "}
                  {/* 使用唯一 id 作为 key */}
                  <Image
                    touchable={true}
                    preventScroll={true}
                    loop={true}
                    src={"http://jingxun.kuxia.top/" + item}
                    alt={item.title}
                  />
                </Swiper.Item>
              ))}
            </Swiper>
          </div>
          <div className={styles.goods_title}>{data.title}</div>
          <div className={styles.goods_price}>￥{data.price}</div>
          <div className={styles.user_discuss}>
            <div>用户评价</div>
            <div className={styles.user_discuss_btn}>
              查看全部
              <img src={require("../img/chevron-right.png")} alt="" />
            </div>
          </div>
          <div className={styles.user_discuss_box}>
            <div className={styles.userinfo}>
              <div className={styles.avatar_box}>
                <img
                  className={styles.avatar}
                  src={require("../img/userAvatar.png")}
                  alt=""
                />
              </div>
              <p>用户9527</p>
            </div>
            <p className={styles.user_discuss_content}>
              宝贝收到了 和卖家描述的一样 质量不错
              很漂亮一直想买这样的，只是这个颜色的稍微有点小瑕疵
            </p>
            <p className={styles.user_discuss_content}>{data.create_time}</p>
            <img
              className={styles.user_discuss_img}
              src={"http://jingxun.kuxia.top/" + data.image}
              alt=""
            />
          </div>
          <div className={styles.discuss_img}>
            {data.banner.split(",").map((item) => (
              <img src={"http://jingxun.kuxia.top/" + item} alt="" />
            ))}
          </div>
        </div>
      ),
    },
    {
      title: "详情",
      content: data ? (
        <div>
          <div className={styles.discuss_img}>
            {data.banner.split(",").map((item) => (
              <img src={"http://jingxun.kuxia.top/" + item} alt="" />
            ))}
          </div>
        </div>
      ) : null,
    },
    {
      title: "评价",
      content: data ? (
        <div className={styles.tabContent}>
          <h3>用户评价（{data.comments?.length || 0}）</h3>
          {data.comments?.map((comment) => (
            <div key={comment.id} className={styles.commentItem}>
              <p>{comment.content}</p>
            </div>
          ))}
        </div>
      ) : null,
    },
  ];

  return (
    <div>
      {/* 顶部导航栏 */}
      <div className={styles.top_box}>
        <img
          src={require("../img/chevron-left.png")}
          onClick={() => navigate(-1)}
          alt="返回"
        />

        <div className={styles.demo_tabs}>
          <Tabs
            active={activeTab}
            onChange={setActiveTab}
            color="#e0af75"
            className={styles.tabs_active}
          >
            {tabContents.map((tab, index) => (
              <Tabs.TabPane key={index} title={tab.title} />
            ))}
          </Tabs>
        </div>

        <img src={require("../img/share.png")} alt="分享" />
      </div>

      {/* 动态内容区域 */}
      <main className={styles.content}>{tabContents[activeTab]?.content}</main>
      <div className="demo-action-bar">
        <ActionBar>
          <ActionBar.Icon icon={<WapHome />} text="主页" />
          <ActionBar.Icon icon={<CartO />} text="购物车" />
          <ActionBar.Button
            style={{ borderRadius: "0px" }}
            color="#E0AF75"
            type="warning"
            text="加入购物车"
          />
          <ActionBar.Button
            style={{ borderRadius: "0px" }}
            color="#FA1E32"
            type="danger"
            text="立即购买"
          />
        </ActionBar>
      </div>
    </div>
  );
}
